import commands, os, re

from user_utils import root_check

def get_free_loop_device():
    
    isroot = root_check()
    if isroot == "no":
        return "You must be root to check the loop device."
    else:
        used_loop_devices = commands.getoutput("losetup -a")
        if used_loop_devices:
            highest_used = max( int(i) for i in re.findall('/dev/loop/?([0-9]+?)', used_loop_devices) )
            highest_used = highest_used + 1
            free_loop = "/dev/loop%s" % highest_used
            return free_loop
        else:
            return "/dev/loop0"

def does_file_exist(path):
    check = os.path.isfile(path)
    return check

def does_folder_exist(path):
    if does_file_exist(path):
        check_path = os.path.dirname(path)
        check = os.path.isdir(check_path)
        return check
    else:
        check = os.path.isdir(path)
        return check

def size_converter(size, needed_unit):
    current_units = size[-2:]
    current_size = size[:-2]
    
    if current_units.lower() == "mb":
        
        if needed_unit.lower() == "kb":
            size=int(current_size) * 1024
            return size
        
        if needed_unit.lower() == "by":
            size=int(current_size) * 1024 * 1024
            return size
        
        if needed_unit.lower() == "gb":
            size=int(current_size) / 1024
            return size
        
        if needed_unit.lower() == "pb":
            size=current_size / 1024 / 1024
            return size
            
    
    